package com.infomanager;

import android.media.AudioManager;
import android.media.MediaPlayer;

import android.widget.Toast;
import android.os.Bundle;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;

import java.util.ArrayList;
import java.util.List;

import java.io.File;

/**
 * Created by Jin on 2016/3/8.
 */
public class MediaModule extends ReactContextBaseJavaModule {

    public MediaModule(ReactApplicationContext reactContext) {
        super(reactContext);
    }

    public MediaPlayer mediaPlayer = new MediaPlayer();
    public boolean isPlaying = false;

    @Override
    public String getName() {
        return "MediaControl";
    }
    @ReactMethod
    public void play(String filePath){

        File file = new File(filePath);
        if(!file.exists()){
            Toast.makeText(getReactApplicationContext(), "此文件不能播放", Toast.LENGTH_SHORT).show();
        }else{

            try{
              if(mediaPlayer!=null && !mediaPlayer.isPlaying()){
              //  mediaPlayer.stop();
                Toast.makeText(getReactApplicationContext(), "开始播放", Toast.LENGTH_SHORT).show();
                mediaPlayer.reset();
                mediaPlayer.setDataSource(filePath);
                mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                mediaPlayer.prepare();       //异步的方式加载音乐文件
                mediaPlayer.start();
                // mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {  //异步加载完音乐文件后会回调此函数
                //     @Override
                //     public void onPrepared(MediaPlayer mp) {
                //         mp.start();               //准备好之后才能start
                //         Toast.makeText(getReactApplicationContext(), "播放状态"+mediaPlayer.isPlaying(), Toast.LENGTH_SHORT).show();
                //     }
                // });

              }else{
                  Toast.makeText(getReactApplicationContext(), "停止播放", Toast.LENGTH_SHORT).show();
                  mediaPlayer.stop();
                  mediaPlayer.release();
              }
              // if(mediaPlayer.isPlaying() && mediaPlayer!=null){

              // }


            }catch(Exception e){
                e.printStackTrace();
            }

          //  Toast.makeText(getReactApplicationContext(), "播放状态："+mediaPlayer.isPlaying(), Toast.LENGTH_LONG).show();
        }
    }
}
